﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class Role_EditController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Manager/Role_Edit.cshtml";
        private string action = CMSEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        public INavigationService _navigation { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("manager_role", CMSEnums.ActionEnum.View.ToString()); //检查权限
            ActionResult result = View(EDIT_RESULT_VIEW);
            string _action = Request.Query["action"];
            int.TryParse(Request.Query["id"],out this.id);

            if (!string.IsNullOrEmpty(_action) && _action == CMSEnums.ActionEnum.Edit.ToString())
            {
                this.action = CMSEnums.ActionEnum.Edit.ToString();//修改类型
                if (this.id == 0)
                {
                    ViewBag.ClientScript = JscriptMsg("传输参数不正确！", "back");
                    filterContext.Result = result;
                    return;
                }
                if (!_manager_role.Exists(this.id))
                {
                    ViewBag.ClientScript = JscriptMsg("角色不存在或已被删除！", "back");
                    filterContext.Result = result;
                    return;
                }
            }
            ViewBag.Action = this.action;
            ViewBag.Id = this.id.ToString();
        }
        //
        // GET: /admin/Role_Edit/

        public ActionResult Index()
        {
            RoleTypeBind(); //绑定角色类型
            NavBind(); //绑定导航
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ShowInfo(this.id);
            }
            else
            {
                ViewData["model"] = new Manager_role();
            }
            return View(WEB_VIEW);
        }

        [HttpPost]
        public ActionResult SubmitSave()
        {
            string result = string.Empty;
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("manager_role", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    result = JscriptMsg("保存过程中发生错误！", "back");
                    return Content(result);
                }
                result = JscriptMsg("修改管理角色成功！", "../role_list/index");
            }
            else //添加
            {
                ChkAdminLevel("manager_role", CMSEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    ViewBag.ClientScript = JscriptMsg("保存过程中发生错误！", "back");
                    return Content(result);
                }
                result = JscriptMsg("添加管理角色成功！", "../role_list/index");
            }
            return Content(result);
        }

        #region 角色类型=================================
        private void RoleTypeBind()
        {
            var model = GetAdminInfo();
            List<SelectListItem> roleList = new List<SelectListItem>();
            roleList.Add(new SelectListItem() { Text = "请选择类型...", Value = "" });
            if (model.role_type < 2)
            {
                roleList.Add(new SelectListItem() { Text = "超级用户", Value = "1" });
            }
            roleList.Add(new SelectListItem() { Text = "系统用户", Value = "2" });
            ViewData["roleList"] = roleList;
        }
        #endregion

        #region 导航菜单=================================
        private void NavBind()
        {
            ViewData["list"] = _navigation.GetList(0, CMSEnums.NavigationEnum.System.ToString());
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            var model = _manager_role.GetModel(_id);
            ViewData["model"] = model;
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            bool result = false;
            Manager_role model = new Manager_role();
            model.role_name = HttpContext.Request.Query["role_name"].FirstOrDefault();
            model.role_type = int.Parse(HttpContext.Request.Query["role_type"].FirstOrDefault());
            string json = HttpContext.Request.Form["json"].FirstOrDefault();
            JObject jobject = JObject.Parse(json);
            JToken record = jobject["list"];
            //管理权限
            List<Manager_role_value> ls = new List<Manager_role_value>();
            foreach (JToken item in record)
            {
                JArray action_types = JArray.FromObject(item["action_type"]);
                foreach (JToken action in action_types)
                {
                    ls.Add(new Manager_role_value { nav_name = item["name"].ToString(), action_type = action.ToString() });
                }
            }
            model.manager_role_values = ls;

            if (_manager_role.Add(model) > 0)
            {
                AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "添加管理角色:" + model.role_name); //记录日志
                result = true;
            }
            return result;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            bool result = false;
            var model = _manager_role.GetModel(_id);

            model.role_name = HttpContext.Request.Query["role_name"].FirstOrDefault();
            model.role_type = int.Parse(HttpContext.Request.Query["role_type"].FirstOrDefault());
            string json = HttpContext.Request.Form["json"].FirstOrDefault();
            JObject jobject = JObject.Parse(json);
            JToken record = jobject["list"];
            //管理权限
            List<Manager_role_value> ls = new List<Manager_role_value>();
            foreach (JToken item in record)
            {
                JArray action_types = JArray.FromObject(item["action_type"]);
                foreach (JToken action in action_types)
                {
                    ls.Add(new Manager_role_value { nav_name = item["name"].ToString(), action_type = action.ToString() });
                }
            }
            model.manager_role_values = ls;

            if (_manager_role.Update(model))
            {
                AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "修改管理角色:" + model.role_name); //记录日志
                result = true;
            }
            return result;
        }
        #endregion
    }
}
